package alipay.openplatform.edu.campus.jiuye.service.services.topic;

import alipay.openplatform.edu.campus.jiuye.common.utils.CopyVoPo;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.dao.mappers.topic.TopicImgInfoMapper;
import alipay.openplatform.edu.campus.jiuye.model.po.TopicImgInfoPO;
import alipay.openplatform.edu.campus.jiuye.model.vo.ImgUrlVO;
import alipay.openplatform.edu.campus.jiuye.model.vo.TopicInfoImgVO;
import alipay.openplatform.edu.campus.jiuye.service.iservice.topic.ITopicImgInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 本实现类用于处理图片
 * Created by gongzhijie on 16/9/18.
 */
@Service
public class TopicImgInfoService implements ITopicImgInfoService {

    @Autowired
    private TopicImgInfoMapper topicImgInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(int topicId,List<ImgUrlVO> imgUrlVOs) {
        List<TopicImgInfoPO> topicImgInfoPOs = changeVOToPO(topicId, imgUrlVOs);
        topicImgInfoMapper.insert(topicImgInfoPOs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByTopicId(Integer topicId, List<ImgUrlVO> imgUrlVOs) {
        //清空数据
        topicImgInfoMapper.deleteByTopicId(topicId);
        List<TopicImgInfoPO> topicImgInfoPOs = changeVOToPO(topicId, imgUrlVOs);
        topicImgInfoMapper.insert(topicImgInfoPOs);
    }

    @Override
    public List<ImgUrlVO> getImgUrlsByTopicId(Integer topicId) {
        List<TopicImgInfoPO> topicImgInfoPOs = topicImgInfoMapper.getImgUrlsByTopicId(topicId);
        return CopyVoPo.copyList(topicImgInfoPOs,ImgUrlVO.class);

    }

    @Override
    public void deleteImgByTopicId(Integer topicId) {
        topicImgInfoMapper.deleteByTopicId(topicId);
    }

    private List<TopicImgInfoPO> changeVOToPO(int topicId,List<ImgUrlVO> imgUrlVOs){
        List<TopicImgInfoPO> topicImgInfoPOs = new ArrayList<TopicImgInfoPO>();
        for (ImgUrlVO imgUrlVO : imgUrlVOs) {
            if (ObjectUtils.isNull(imgUrlVO)){
                continue;
            }
            TopicImgInfoPO topicImgInfoPO = new TopicImgInfoPO();
            topicImgInfoPO.setTopicId(topicId);
            topicImgInfoPO.setImgUrl(imgUrlVO.getImgUrl());
            topicImgInfoPO.setIsLogo(imgUrlVO.getIsLogo());
            topicImgInfoPOs.add(topicImgInfoPO);
        }
        return topicImgInfoPOs;
    }
}
